/**
 * Created by IntelliJ IDEA.
 * User: szwl
 * Date: 20.09.11
 * Time: 11:53
 * To change this template use File | Settings | File Templates.
 */

import java.net.ServerSocket
import groovy.xml.*

class DummyServer {

    public static void main(String[] args) {

        println "${new Date().format('HH:mm:ss')} starting dummy server..."
        if (args.length < 1) {return;}
        def server = new ServerSocket(args[0].toInteger())

        while (true) {
            server.accept { socket ->
                println "${new Date().format('HH:mm:ss')} processing new connection..."
                socket.withStreams { input, output ->
                    Thread.start {
                        println "${new Date().format('HH:mm:ss')} started ping thread..."
                        def run = true
                        while (run) {
                            sleep(1000 * 5) {run = false}
                            try {
                                output << '<ping/>\0'
                                println "${new Date().format('HH:mm:ss')} ping sent..."
                            }
                            catch(SocketException e){
                                println "${new Date().format('HH:mm:ss')} ping thread detected disconnection of client..."
                                run = false
                            }
                        }
                    }
                    output << '<connect server="2.0"> asd </connect>\0'
                    output << '<process-exclusion excluded="+" subject=".*" action="agentsvr.exe" object="C:\\WINDOWS\\msagent\\agentsvr.exe"/>\0'
                    output << '<process-exclusion excluded="+" subject=".*" action="agentsvr.exe" object="C:\\WINDOWS\\agentsvr.exe"/>\0'
                    output << '''<visit-event identifier=”group1” program="iexplore" time="5">
<item url="http%3A%2F%2Fwww.google.com"/>
<item url="http%3A%2F%2Fwww.cnn.com"/>
<item url="http%3A%2F%2Fwww.yahoo.com"/>
<item url="http%3A%2F%2Fwww.slashdot.org"/>
</visit-event>\0'''
                    def reader = input.newReader()
                    def buffer;

                    while ((buffer = reader.readLine()) != null) {

                        println "${new Date().format('HH:mm:ss')} received: " + buffer

                    }

                }
                println "${new Date().format('HH:mm:ss')} processing/thread complete."

            }

        }

    }

}
